package com.xuegao.xuegaoremotelogin.controller;

import com.xuegao.xuegaoremotelogin.constant.Cache;
import com.xuegao.xuegaoremotelogin.domain.UserInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * <br/> @PackageName：com.xuegao.xuegaoremotelogin.controller
 * <br/> @ClassName：LoginController
 * <br/> @Description：
 * <br/> @author：xuegao
 * <br/> @date：2021/03/04 20:03
 */
@RestController
public class LoginController {

    @PostMapping(path = "/login")
    public void login(HttpServletRequest request,
                      HttpServletResponse response,
                      UserInfo userInfo) throws IOException, ServletException {
        System.out.println("=========================================");

        HttpSession session = request.getSession();
        //将当前用户添加到session
        session.setAttribute("username", userInfo);

        String username = userInfo.getUsername();
        String sessionId = session.getId();
        // 不存在，首次登陆，放入Map
        if (Boolean.FALSE.equals(Cache.SESSION_MAP.containsKey(username))) {
            Cache.SESSION_MAP.put(username, sessionId);
            System.out.println("不存在，首次登陆，放入Map = " + Cache.SESSION_MAP);
        } else if (Cache.SESSION_MAP.containsKey(username) &&
                Boolean.FALSE.equals(sessionId.equals(Cache.SESSION_MAP.get(username)))) {
            Cache.SESSION_MAP.remove(username);
            Cache.SESSION_MAP.put(username, sessionId);
            System.out.println("异地登录 = " + Cache.SESSION_MAP);
        }
        response.sendRedirect("index.html");
        System.out.println(userInfo);
        System.out.println("=========================================");
    }

    @GetMapping(path = "/loginOut")
    public void logOut(HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        response.sendRedirect("login.html");
    }

    @GetMapping(path = "/q")
    public void q(HttpServletRequest request,
                  HttpServletResponse response) throws IOException {
        Cache.SESSION_MAP.clear();
        System.out.println(Cache.SESSION_MAP);
    }

    @GetMapping(path = "/index")
    public void in(HttpServletResponse response) throws IOException {
        response.sendRedirect("index.html");
    }
}
